package fafu.comedu.workerrepair.command;

import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.io.File;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UploadUtil {
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 1000;//超时时间
    private static final String CHARSET = "utf-8";//设置编码

    /**
     * android上传文件到服务器
     *
     * @param file       需要上传的文件
     * @param RequestURL  请求的url
     * @return 返回响应的内容
     */
    public static Integer uploadImage(File file, String RequestURL) {
        // MultipartBuilder，是上传文件的query
        // addFormDataPart方法：@param [String]name, [String]value
        // addFormDataPart方法：@param [String]name, [String]fileName, [String]fileType, [String]file
        Integer id = -1;
        if(file.isDirectory())
            Log.i(TAG, "uploadImage: is a directory");
        if(!file.exists())
            Log.i(TAG, "uploadImage: file not exists");
        else
            Log.i(TAG, "uploadImage: file exists");
        String name = file.getName();
        Log.i(TAG, "uploadImage: "+name);
        RequestBody image = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file",file.getName(),image)
                .build();
        Log.i(TAG, "uploadImage: creat requestBody");
        Request request = new Request.Builder()
                .url(RequestURL)
                .post(requestBody)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            String json = response.body().string();
            Log.i(TAG, "uploadImage: "+json);
            ReJsonRsp reJsonRsp = JSONObject.parseObject(json,new TypeReference<ReJsonRsp>(){});
            JSONObject data = (JSONObject) reJsonRsp.getData();
            id = (Integer) data.get("picId");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return id;
    }

    private static String getMIMEType(File file) {
        String fileName = file.getName();
        if (fileName.endsWith("png") || fileName.endsWith("PNG")) {
            return "image/png";
        } else {
            return "image/jpg";
        }
    }
}
